import axios from "axios";
import router from "./router";
import store from "./store"
import Element from "element-ui";

axios.defaults.baseURL = "http://localhost:8080"
const request = axios.create({
    timeout: 5000,
    headers: {
        "Content-Type": "application/json; charset=utf-8"
    }
})

request.interceptors.request.use(config => {
    config.headers['authorization'] = localStorage.getItem("token")
    return config
})

request.interceptors.response.use(response => {

    let res = response.data;
    if(res.success){
        return response
    } else{
        Element.Message.error(res.message? res.message:'系统异常')
        return Promise.reject(res.message)
    }
},error => {

    if(error.response.data){
        error.message = error.response.data.message
    }
    if(error.response.status === 403){
        error.message = "请求参数非法"
    }else
    if(error.response.status === 404){
        error.message = "API接口路径错误"
    }else
    if(error.response.status === 401){
        store.commit("resetState")  
        router.replace("/login")      
        // location.reload();
    }
    Element.Message.error(error.message,{duration:3000})
    return Promise.reject(error.message)
})

export default request